package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.StrategyTheme;
import cn.wolfcode.luowowo.query.QueryObject;
import cn.wolfcode.luowowo.repository.StrategyThemeRepository;
import cn.wolfcode.luowowo.service.IStrategyThemeService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
//@Transactional //事务最后处理
public class StrategyThemeServiceImpl implements IStrategyThemeService {

    @Autowired
    private StrategyThemeRepository repository;

    @Autowired
    private MongoTemplate template;


    @Override
    public StrategyTheme get(String id) {
        Optional<StrategyTheme> optional = repository.findById(id);
        if (optional != null) {
            return optional.get();
        }
        return null;
    }

    @Override
    public Page<StrategyTheme> query(QueryObject qo) {
        //List<StrategyTheme> list = repository.findAll(); //使用repostory对象查询的结果不满足带条件查询
        //使用MongoTemplate，可以满足条件查询，但是返回的是list集合，如何封装成Page对象？
        Query query = new Query();
        //PageImpl构造器的参数3：total
        long total = template.count(query, StrategyTheme.class);

        if (total == 0) {
            //总条数为0 就返回空的page回去
            return Page.empty();
        }
        //PageImpl构造器的参数2：pageable
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "_id");
        query.with(pageable);
        //PageImpl构造器的参数1：list
        List<StrategyTheme> list = template.find(query, StrategyTheme.class);

        return new PageImpl<StrategyTheme>(list, pageable, total);
    }

    @Override
    public void update(StrategyTheme strategyTheme) {
        //使用save方法是全量更新，如果更新部分，会出现未更新的字段被null覆盖
        //repository.save(strategyTheme);

        //方案一：查询————替代————保存（效率低，用update）
        //方案二：显示使用update逻辑 update set...

        //条件对象
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(strategyTheme.getId()));

        //使用工具简化更新的代码
        DBHelper.update(template, query, strategyTheme,"name","state","sequence");

    }

    @Override
    public void save(StrategyTheme strategyTheme) {
        repository.save(strategyTheme);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public List<StrategyTheme> list() {
        return template.findAll(StrategyTheme.class);
    }


}
